package com.shiliu.api.common.utils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @description: Redis工具类,操作的是String类型数据结构
 * @author: shiliu
 * @created: 2019/12/22 15:34
 * @version: v1.0.0
 */
@Component
@Data
@Slf4j
public class JedisUtil {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 默认过期时长，单位：秒
     */
    public static final long DEFAULT_EXPIRE = 30 * 60;

    /**
     * 不设置过期时长
     */
    public static final long NOT_EXPIRE = -1;

    /**
     * HASH KEY的值
     */
    private static final String HASH_TOKEN="token:";

    /**
     * 设值
     *
     * @param key
     * @param value
     */
    public void set(String key,String value){
        redisTemplate.opsForValue().set(HASH_TOKEN + key,value);
    }

    /**
     * 设值
     *
     * @param key
     * @param value
     * @param expireTime 过期时间, 单位: s
     */
    public void set(String key,String value,long expireTime){
        if(expireTime == 0 || expireTime != NOT_EXPIRE){
            // 默认过期时间30分钟
           expireTime = DEFAULT_EXPIRE;
        }
        redisTemplate.opsForValue().set(HASH_TOKEN + key,value,expireTime,TimeUnit.SECONDS);
    }

    /**
     * 取值
     *
     * @param key
     * @return
     */
    public String get(String key){
        return redisTemplate.opsForValue().get(HASH_TOKEN + key);
    }

    /**
     * 删除key
     *
     * @param key
     * @return
     */
    public boolean delete(String key){
        Boolean delete = redisTemplate.delete(HASH_TOKEN + key);
        return delete;
    }

    /**
     * 判断key是否存在
     *
     * @param key
     * @return
     */
    public Boolean exists(String key){
        Boolean hasKey = redisTemplate.hasKey(HASH_TOKEN + key);
        return hasKey;
    }

    /**
     * 设值key过期时间
     *
     * @param key
     * @param expireTime 过期时间, 单位: s
     * @return
     */
    public Boolean setExpireTime(String key,long expireTime){
        if(expireTime == 0 && expireTime != NOT_EXPIRE){
            // 默认过期时间30分钟
            expireTime = DEFAULT_EXPIRE;
        }
        Boolean expire = redisTemplate.expire(HASH_TOKEN + key, expireTime, TimeUnit.SECONDS);
        return expire;
    }

    /**
     * 获取剩余时间

     *
     * @param key
     * @return
     */
    public long getExpireTime(String key){
        return redisTemplate.getExpire(HASH_TOKEN + key, TimeUnit.SECONDS);
    }

}
